如何从B表中只选择一行?

时间:2015-05-01 11:13:35

标签: php database select

我有两张桌子:

sma_db

+----+----------+-------+
| ID |  title   | catid |
+----+----------+-------+
| 1  | Hi       |   4   |
| 2  | Hello    |   4   |
| 3  | Test     |   5   |
+----+----------+-------+

sma_files

+----+----------+---------+
| ID |  name    |entry_id |
+----+----------+---------+
| 1  | a.jpg    |    1    |
| 2  | b.jpg    |    1    |
| 3  | c.jpg    |    2    |
+----+----------+---------+

我的查询为:

$sql = mysql_query("SELECT * FROM sma_db 
                    LEFT OUTER JOIN sma_files 
                    ON sma_db.id = sma_files.entry_id 
                    WHERE catid = '4'") or die(mysql_error());;

while($affcom = mysql_fetch_assoc($sql)){ 
     $title = $affcom['title'];
     $name = $affcom['name'];
     echo $title; 
     echo $name; 
}

如何从 sma_files 表中仅选择一行???

以上查询的输出:

Hi    a.jpg
Hi    b.jpg
Hello c.jpg

我需要的输出:

Hi    a.jpg
Hello c.jpg

3 个答案:

答案 0 :(得分:2)

$sql = mysql_query("SELECT * FROM sma_db 
                    LEFT OUTER JOIN sma_files 
                    ON sma_db.id = sma_files.entry_id 
                    WHERE catid = '4' 
                    GROUP BY sma_files.entry_id") 
                    or die(mysql_error());

答案 1 :(得分:0)

使用Group By

SELECT * FROM sma_db 
LEFT OUTER JOIN sma_files 
ON sma_db.id = sma_files.entry_id 
WHERE catid = '4'
GROUP BY `entry_id`

答案 2 :(得分:0)

尝试以下查询

SELECT * FROM `sma_db` 
INNER JOIN `sma_files` 
ON `sma_db`.`id` = `sma_files`.`entry_id` 
WHERE `sma_db`.`catid` = '4'"