table1:
id bgcolor
1 #333333
2 #666666
3 #999999
table2
id table1_id clothes
5 1 男式T恤
8 2 女式T恤
3 3 中性T恤
table3
id table2_id mytime color
1 5 2014-06-01 白色
2 5 2014-06-02 灰色
3 5 2014-06-03 绿色
table4
id table2_id mytime styles
3 5 2014-06-13 中国风
4 5 2014-06-29 欧美式
5 5 2014-07-15 怀旧式
如何让mysql的join的连接查询中的子表多加个条件
如果
table2.id=table3.table2_id
table2.id=table4.table2_id
因为table3和table4中的table2_id是有重复的
所以查询出的数据也会重复,如何再进一步根据mytime取出最新数据
下面是实计项目中的尝试:
例子1:$sql = "SELECT `score_size`.`size_disc`, `score_disc`.`Dish`, `category`.`bgcolor`, `data`.`id`, `data`.`Weeks`, `data`.`League`, `data`.`The_main`, `data`.`The_guest`, `data`.`The_game_time`, `data`.`The_weather`, `data`.`Half_score`, `data`.`Full_score`, `data`.`Half_size`, `data`.`Full_size`, `data`.`Disc_Half_score`, `data`.`Disc_Full_score`, `data`.`Disc_Half_size`, `data`.`Disc_Full_size` FROM `score_size`, `score_disc`, `data`, `category` WHERE `data`.`id`=(SELECT `id` FROM score_size ORDER BY id DESC LIMIT 0, 1) AND `data`.`id`=(SELECT `id` FROM score_disc ORDER BY id DESC LIMIT 0, 1) AND `category`.`id`=`data`.`category_id` ORDER BY `Ydata`.`The_game_time` ASC";
查询结果为空....
例子2:基于CI框架
$select = 'score_1size.size_disc, score_disc.Dish, category.bgcolor, data.id, data.Weeks, data.League, data.The_main, data.The_guest, data.The_game_time, data.The_weather, data.Half_score, data.Full_score, data.Half_size, data.Full_size, data.Disc_Half_score, data.Disc_Full_score, data.Disc_Half_size, data.Disc_Full_size';
$where = array(
'score_size.create_time'=>'(select max(create_time) from score_size)',
'score_disc.create_time'=>'(select max(create_time) from score_disc)'
);
$D = $this->db->where($where)->select($select)->join('score_size', 'data.id=score_size.data_id')->join('score_disc', 'data.id=score_disc.data_id')->join('category', 'category.id=data.category_id', 'left')->order_by('data.The_game_time asc, score_disc.id desc, score_size.id desc')->get('data');
把->where($where)去掉的情况
只要data.id=score_disc.data_id和data.id=score_size.data_id都成立的将会全部查询出来
所以例子2会查询出重复值
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
试试这个。
要以 颜色表作为基准去join其他表。
按照你的数据输出了,有9条, 3(style) x 3(color) x 1(tshit) = 9。
不知道你想要的是不是要查看这个效果?

我是这样写的: