我有一个HTML表单,它在下表中搜索firstname,lastname,address(以及我在这里为了简单起见留下的其他几个列):
MEMBERS
id | firstname | lastname
---+-----------+-----------
1 | Jon | Doe
2 | Mary | Smith
3 | Jon | James
ADDRESSES
id | member_id | address
---+-----------+-----------
1 | 1 | Home address
2 | 1 | Work address
3 | 2 | Home address
4 | 3 | Home address
5 | 3 | Work address
6 | 3 | Holiday address
会员可以拥有无限数量的地址。
如何搜索所有出现的'Jon'作为名字,但只显示第一个地址?例如:
Jon Doe Home address
Jon James Home address
到目前为止,这是我们的mySQL声明:
SELECT * FROM tbl_members T1 INNER JOIN tbl_addresses T2 ON T1.id = T2.member_id WHERE firstname = 'Jon'
我们也尝试过:
SELECT * FROM tbl_members T1 LEFT JOIN tbl_addresses T2 ON T1.id = T2.member_id WHERE firstname = 'Jon'
这两个陈述都给了我们:
Joh Doe Home address
Jon Doe Work address
Jon James Home address
Jon James Work address
Jon James Holiday address
非常感谢您的帮助!
答案 0 :(得分:2)
您可以使用LIMIT
关键字:
SELECT * FROM tbl_members T1 INNER JOIN tbl_addresses T2 ON T1.id = T2.member_id WHERE firstname = 'Jon' LIMIT 1
答案 1 :(得分:1)
嗨,我认为你应该这样做:
SELECT T1.firstname, T1.lastname, T2.address
FROM MEMBERS AS T1
INNER JOIN (SELECT member_id, address
FROM ADDRESSES
GROUP BY member_id) AS T2
ON T1.id = T2.member_id
以下是SQL Fiddle,了解它是如何工作的......
GL!
修改强>
当然,如果您需要,可以在查询结尾添加WHERE子句,从表或名称组中选择特定名称,如
WHERE firstname = 'joe'
或任何......
Hire is a Fiddle为此...
答案 2 :(得分:1)
您可以在SQL语句中添加GROUP BY
子句
SELECT firstname, lastname, address
FROM members
JOIN addresses ON members.id = addresses.member_id
WHERE firstname = 'Jon'
GROUP BY members.id;
答案 3 :(得分:0)
尝试使用关键字 LIMIT ,如here所述。
使用LIMIT 1
,您将查询限制为返回的第一行。