I have a database-driven FAQ that is organised into sections and I am trying to get the section data for only those sections who have a question/answer associated with them.
我有一个数据库驱动的常见问题解答,它被组织成各个部分,我试图只获得那些有问题/答案的部分的部分数据。
Here is the schema:
这是架构:
|---------------------| |----------------------|
| Section | | Quest-Ans |
|---------------------| |----------------------|
| PK | id(int) |<--| | PK | id(int) |
| | title(varchar) | |--| FK | Sec_id(int) |
| | desc(text) | | | body(text) |
|---------------------| |----------------------|
When I try this query:
当我尝试这个查询时:
SELECT DISTINCT s.id, s.title, s.desc
FROM Section as s INNER JOIN Quest-Ans as q ON s.id = q.Sec_id
I get an error saying that DISCRETE cannot be applied to a text field. How can I get the data I want?
我收到一条错误消息,说DISCRETE无法应用于文本字段。我怎样才能获得我想要的数据?
If it matters, this is an SQL2000 database.
如果重要,这是一个SQL2000数据库。
EDIT:
Ok, so it seems like there are two ways to go about this. Either with EXISTS and a subquery in the where clause, or with the subquery in the inner join. Which is faster?
好的,所以似乎有两种方法可以解决这个问题。使用EXISTS和where子句中的子查询,或者使用内部联接中的子查询。哪个更快?
4 个解决方案
#1
This should do it:
这应该这样做:
SELECT s.id, s.title, s.desc
FROM Section as s
WHERE EXISTS (SELECT * FROM Quest-Ans as q where q.Sec_id = s.id)
#2
select s.id, s.title, s.desc
from Section s
inner join (select distinct sec_id from Quest-Ans) dqa on s.id = dqa.sec_id
#3
Try it:
SELECT s.Title, s.Desc
FROM Section as s
INNER JOIN (
SELECT DISTINCT s.id
FROM Section as s
INNER JOIN Quest-Ans as q ON s.id = q.Sec_id
) q ON s.Id = q.Id
#4
try CONVERT , DISTINCT CONVERT(VARCHAR(500), "text field")
尝试CONVERT,DISTINCT CONVERT(VARCHAR(500),“text field”)
#1
This should do it:
这应该这样做:
SELECT s.id, s.title, s.desc
FROM Section as s
WHERE EXISTS (SELECT * FROM Quest-Ans as q where q.Sec_id = s.id)
#2
select s.id, s.title, s.desc
from Section s
inner join (select distinct sec_id from Quest-Ans) dqa on s.id = dqa.sec_id
#3
Try it:
SELECT s.Title, s.Desc
FROM Section as s
INNER JOIN (
SELECT DISTINCT s.id
FROM Section as s
INNER JOIN Quest-Ans as q ON s.id = q.Sec_id
) q ON s.Id = q.Id
#4
try CONVERT , DISTINCT CONVERT(VARCHAR(500), "text field")
尝试CONVERT,DISTINCT CONVERT(VARCHAR(500),“text field”)