table :First
..............................................................................
id | ros | table | column | stool | date | places|
..............................................................................
1 12 5 6 a 2017-07-17 goa |
2 12 5 6 b 2017-07-17 delhi|
..............................................................................
table :second
..........................................................................
id | ros | name | email | phone | stos|address |date |
....................................................................................................
5 12 and and@her.com 394924673464 6 fddsfds 2017-07-03 |
6 12 her her@and.com 84838593894 6 fdafdfd 2017-07-04 |
....................................................................................................
Query like I am Using:
SELECT `p`.* FROM `first` `p` LEFT JOIN `second` as `st` ON `st`.`ros`=`p`.`ros` ORDER BY `id` DESC LIMIT 10;
我的问题是为什么它返回4行而不是2行? 它没有在表格中恢复4值我是否需要使用distinct或group by?
答案 0 :(得分:2)
尝试此查询:
SELECT p.* FROM first as p LEFT JOIN second as st ON st.site_id=p.site_id group by p.id ORDER BY p.id DESC LIMIT 10;
答案 1 :(得分:2)
返回4列因为您的表格有重复site_id
。
使用此更改您的查询。这将只返回2行。
SELECT `p`.* FROM `first` `p` LEFT JOIN `second` as `st` ON `st`.`site_id`=`p`.`site_id` GROUP BY p.id ORDER BY `id` DESC LIMIT 10;
答案 2 :(得分:1)
它返回4行,因为两个表中的所有site_id都是11.要使它成为两列,只需在sql语句中添加Group By。
就像:
SELECT `p`.* FROM `first` `p` LEFT JOIN `second` as `st` ON
`st`.`site_id`=`p`.`site_id` GROUP BY `p`.`id` ORDER BY `id` DESC LIMIT 10;
答案 3 :(得分:0)
你问题的答案"为什么"是:这是正常的,因为您加入site_id
并且第一个表中的每一行在第二个表中都有2个匹配的site_id's
行,因此2 * 2 = 4
#first table
+-----+---------+
| id | site_id |
+-----+---------+
| 31 | 11 |
+-----+---------+
| 32 | 11 |
+-----+---------+
# second table
+-----+---------+
| id | site_id |
+-----+---------+
| 5 | 11 |
+-----+---------+
| 6 | 11 |
+-----+---------+
当您从{1}}的第一个表格加到第二个表格时,您将获得2行site_id
当您从{1}}的第一个表到第二个表加入32时,您将获得2行(31 with 5, and 31 with 6)
你需要将结果分组给@Sonu Bamniya说