从数据库表中获取类似的行

时间:2011-04-29 10:36:20

标签: mysql sql sql-server

你好朋友我有以下表结构 引用表

enter image description here

我想访问特定_id(quoteId)的所有类似引号(具有相同的author_id和category_id)

类似的引号意味着此表的所有那些行的所有列都具有相同的category_id和相同的author_id。如果两个引用的作者相同且类别相同,则可以认为它们是相似的。

2 个答案:

答案 0 :(得分:1)

select 
    q1.* 
from 
    quotes q1
inner join 
   (select
      author_id,
      category_id
    from 
        quotes
    where 
        _id = 1) q2
ON 
    q1.author_id = q2.author_id
AND 
    q1.category_id = q2.category_id

答案 1 :(得分:1)

相同的作者ID和类别ID?

SELECT `related_quote`.*
FROM `quote` AS `main_quote`
LEFT JOIN `quote` AS `related_quote` USING(`author_id`, `category_id`)
WHERE `main_quote`.`_id` = QUOTE_ID

这将为您提供原始报价(即QUOTE_ID),以及与之相关的所有报价。

mysql> SELECT `related_quote`.*
    -> FROM `quote` AS `main_quote`
    -> LEFT JOIN `quote` AS `related_quote` USING(`author_id`, `category_id`)
    -> WHERE `main_quote`.`_id` = 1;
+------+----------------+-----------+-------------+
| _id  | content        | author_id | category_id |
+------+----------------+-----------+-------------+
|    1 | test           |         1 |           1 |
|    2 | test related   |         1 |           1 |
|    3 | test related 2 |         1 |           1 |
+------+----------------+-----------+-------------+
3 rows in set (0.01 sec)

只需添加

即可从结果集中删除QUOTE_ID
AND `related_quote`.`_id` != QUOTE_ID

到查询结尾。