开发者

Query from 2 pseudotables, hosted in the same real table

Let there are 2 tables. To query the rows, which have the same IDs, you have to do this:

SELECT * FROM Table1 A, Table2 B WHERE A.id = B.id

Now let the tables be merged into one global table, with an added ex-table column. So, query

SELECT * FROM Table1

now looks like:

SELECT * FROM GlobalTable WHERE tableId = 1

But how the first query should look now?

SELECT * FROM Table1 A, Table2 B WHERE A.id = B.开发者_开发百科id

?


One table should store one entity. There is no such thing as a "one true lookup table" or "global table". Nor should you consider an EAV. This question assumes all your tables have the same layout...

However, I look forward to more rep later when it doesn't work properly so...

You should use explicit JOINs to separate filter and join conditions

Select *
from
   GlobalTable A
   JOIN
   GlobalTable B ON A.id = B.id
WHERE
    A.tableId = 1 AND B.tableId = 2

If you need to do an OUTER JOIN, then you can write this

Select *
from
   (SELECT * FROM GlobalTable WHERE tableId = 1) A
   LEFT JOIN
   (SELECT * FROM GlobalTable WHERE tableId = 2) B ON A.id = B.id

I'd suggest using an indexed view though to persist "tableA" and "tableB" as separate objects to avoid this continual filtering. Or don't merge them...

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜