简体   繁体   中英

Show all results from 1st table but only 1st result from 2nd table in mySql join statement

I have a HTML form which searches for firstname, lastname, address (and several other columns which I have left out here for simplicity) in the following tables:

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

A member can have an unlimited number of addresses.

How do I search for all occurences of 'Jon' as firstname but only display the first address? For example:

Jon Doe Home address
Jon James Home address

This is our mySQL statement so far:

SELECT * FROM tbl_members T1 INNER JOIN tbl_addresses T2 ON T1.id = T2.member_id WHERE firstname = 'Jon'

We have also tried:

SELECT * FROM tbl_members T1 LEFT JOIN tbl_addresses T2 ON T1.id = T2.member_id WHERE firstname = 'Jon'

Both these statements give us:

Joh Doe Home address 
Jon Doe Work address 
Jon James Home address 
Jon James Work address 
Jon James Holiday address

Many thanks for any help!

You can use LIMIT keyword:

SELECT * FROM tbl_members T1 INNER JOIN tbl_addresses T2 ON T1.id = T2.member_id WHERE firstname = 'Jon' LIMIT 1

Reference: https://dev.mysql.com/doc/refman/5.0/en/select.html

Hi I think you should do something like this:

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

Here is SQL Fiddle for that to see how it's work...

GL!

EDIT:

Of course if you need you can add WHERE clause at the end of query to select specific name from table or group of name like

WHERE firstname = 'joe'

or whatsoever...

Hire is a Fiddle for that...

You can add a GROUP BY clause to your SQL statement

SELECT firstname, lastname, address
FROM members
JOIN addresses ON members.id = addresses.member_id
WHERE firstname = 'Jon'
GROUP BY members.id;

Try using the keyword LIMIT , as described here .

Using LIMIT 1 , you'll limit your query to the first row returned.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM