我有一张tbl_customers
表。 (像许多人一样)
我有第二张桌子:tbl_customers_tags
这张表只是让我为单个客户记录存储无限的关键字/标签。 这是列结构:
`tbl_customers_tags`
+-------------+---------------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-------------+---------------------+------+-----+---------+----------------+
| ID | int(11) unsigned | NO | PRI | NULL | auto_increment |
| customerid | int(11) unsigned | NO | MUL | NULL | |
| tagid | mediumint(5)unsigned| NO | | NULL | |
所以,我现在需要通过查找具有某些tagid的任何客户端记录来提取一些报告。我正在重复。 这是我当前的查询语句:
SELECT c.firstname, c.lastname, c.datecreated
FROM `tbl_customers` c
LEFT JOIN `tbl_customers_tags` ctags ON c.customerid = ctags.customerid
WHERE ctags.tagid IN(2,3,15)
当单个customerid
与多个tagid
记录相关联时,是否有办法不返回重复项?
答案 0 :(得分:0)
SELECT distinct c.firstname, c.lastname, c.datecreated
FROM `tbl_customers` c
LEFT JOIN `tbl_customers_tags` ctags ON c.customerid = ctags.customerid
WHERE ctags.tagid IN(2,3,15)
答案 1 :(得分:0)
如果您真的不关心重复项,可以使用DISTINCT
关键字。此外,您不需要执行LEFT OUTER JOIN
,因为您有WHERE
子句依赖于另一个表。像这样:
SELECT DISTINCT c.firstname, c.lastname, c.datecreated
FROM `tbl_customers` c
JOIN `tbl_customers_tags` ctags
ON c.customerid = ctags.customerid
WHERE ctags.tagid IN (2,3,15)
答案 2 :(得分:0)
试试这个
SELECT c.firstname, c.lastname, c.datecreated
FROM 'tbl_customers' c
where exists
( select 'x' from tbl_customers_tags where customerid = c.customerid and
tagid IN(2,3,15)
)
如果您只对标签表中有记录的客户感兴趣,为什么不进行完全加入而不是左转?