我有2个数据库表:
表1:
+---------+-------+-------------+
| Page | Title | Description |
+---------+-------+-------------+
| Apple | ..... | ........... |
| Orange | ..... | ........... |
| Pear | ..... | ........... |
| Grapes | ..... | ........... |
+---------+-------+-------------+
表2:
+----------+-------------+
| Link | Page |
+----------+-------------+
| Website1 | Apple |
| Website2 | Orange |
| Website3 | Apple |
| Website4 | Orange |
| Website5 | Apple |
| Website6 | Pear |
| Website7 | Apple |
| Website8 | Grapes |
| Website9 | Grapes |
+----------+-------------+
我想知道/返回表2中引用表1中的页数以及它们被引用的次数。 (我不想知道表2中引用了表1中每个页面的次数。)
所以在这个例子中: 1页被引用1次(梨), 2页被引用2次(Grapes和Orange)& 1页被引用4次。
我会用什么样的SQL语句来获取它?
答案 0 :(得分:0)
以下查询应该做..
SELECT COUNT(1) NoOfPages,CNT ReferencedTimes
FROM
(
SELECT T2.PAGE,COUNT(1) CNT
FROM TABLE1 T1 INNER JOIN TABLE2 T2 ON T1.PAGE = T2.PAGE
GROUP BY T2.PAGE
)T
GROUP BY CNT
答案 1 :(得分:0)
我认为以下陈述适合:
SELECT count(*) FROM Table2 WHERE (Table2.Page IN (SELECT Page FROM Table1));
答案 2 :(得分:0)
SELECT (GROUP_CONCAT(DISTINCT page)) AS Page,page_count
FROM
(SELECT table1.Page as page,COUNT(*) as page_count
FROM table1 INNER JOIN table2 ON table1.Page=table2.Page
GROUP BY table1.Page)
as T GROUP BY page_count
希望这有帮助
答案 3 :(得分:0)
使用此查询
1) User_Test::test_Query
Unable to find JSON fragment ["data":[{"username":"1137598_update"}]] within [{"current_page":1,"data":[{"updated_at":"2015-10-29 18:57:13","username":"1137598_update"}]}].
Failed asserting that false is true.
答案 4 :(得分:0)
如果您要搜索的是X页面被引用了N次,则以下查询将实现:
SELECT COUNT(t1.page), t2.count
FROM table1 t1
INNER JOIN (SELECT page,COUNT(*) AS count FROM table2 GROUP BY page) t2 ON t1.page=t2.page
GROUP BY t2.count
答案 5 :(得分:0)
尝试此查询,它将进行左连接并告诉您在table2中引用项目的次数,如果count为零而不是其他表中没有引用
SELECT table1.Page, count(table2.Page) as count
FROM table1
LEFT JOIN table2 ON table2.Page = table1.Page
GROUP BY table1.Page