Search code examples
mysqlselectjoinexpressionengine

Specific MySQL Query: Combining Two MYSQL Select Statements with OR


I need to check if an entry is categorized (query A) OR if an entry has a relationship with certain data (query B). I'd like to do this with one query rather than two separate queries. For example:

[if query A OR query B ]
   <p>Show this content</p>
[/if]

I have the two select queries working correctly, but only independently of one another. They are:

Query A:

SELECT entry_id FROM exp_category_posts WHERE entry_id = '999' AND cat_id IN(SELECT cat_id FROM exp_categories WHERE group_id = '5') LIMIT 1

Query B:

SELECT entry_id FROM exp_matrix_data WHERE field_id = '19' AND col_id_7 <> '' AND entry_id = '999'

Again, I'd like to combine these two queries into a single query that checks if entry 999 is EITHER categorized in certain categories (query A) OR has a relationship with certain data (query B). What is the best way to do this?

If it helps, the queries are being run on an ExpressionEngine database.

Disclaimer: I know there are plenty of questions on SO on how to combine MySQL SELECT statements, but I am looking for help on this specific query, and didn't find any questions similar enough to my own. My apologies in advance if I have inadvertently angered the duplicate question gods.


Solution

  • As your entry comes from two different tables and, as I understand your request, it doesn't have to exist in both of them, you would need a FULL OUTER JOIN to do it with OR, which is not supported in MySQL.

    However, you can use a UNION to get your desired result:

    SELECT entry_id FROM exp_category_posts WHERE entry_id = '999' AND cat_id IN(SELECT cat_id FROM exp_categories WHERE group_id = '5') LIMIT 1
    UNION DISTINCT
    SELECT entry_id FROM exp_matrix_data WHERE field_id = '19' AND col_id_7 <> '' AND entry_id = '999'