mysql query with AND, OR and NOT - mysql

Lets say I have a table of articles with as many to many relationship with topics. Each topic assigned to an article has a type field which can contain 1 of 3 values AND, NOT, and OR.
Articles
id
....
Topics
id
....
ArticleTopics
article_id
topic_id
type
I want to create a query that says returns all articles that have:
ALL of the following topics: 1, 2, 3 (AND association)
AND
ANY of the following topics: 4, 5, 6 (OR association)
AND
NONE of the following topics 7, 8 (NOT association)
How do I go about creating this query?
Thanks in advance!

The ALL and NOT parts are very simple, you just chain them with ANDs:
SELECT X FROM Y WHERE a AND b AND c AND NOT d AND e AND NOT e.
And the ORs go between:
SELECT X FROM Y WHERE ((a AND b AND c) AND (d OR e OR f)) AND NOT g AND NOT h
replace small numbers with comparisons and you're done.
So if you want to do this in code, sort your conditions and then just chain them together as a String. Be careful to avoid SQL-Insertions.

If I get this correctly
SELECT * FROM ArticleTopics where type = 'AND'
UNION
SELECT * FROM ArticleTopics where type = 'OR' limit 1
I assume by 'any' you mean 'any one'. You can join the articles to topics yourself, that's trivial.

SELECT a.id, a.name
FROM Articles a, ArticleTopics arto
WHERE arto.article_id = a.id
AND
((arto.topic_id = 1 AND arto.type like 'AND') AND (arto.topic_id = 2 AND arto.type like 'AND') AND (arto.topic_id = 3 AND arto.type like 'AND'))
AND
((arto.topic_id = 4 AND arto.type like 'OR') AND (arto.topic_id = 5 AND arto.type like 'OR') AND (arto.topic_id = 6 AND arto.type like 'OR'))
AND
((arto.topic_id = 7 AND arto.type like 'NOT') AND (arto.topic_id = 8 AND arto.type like 'NOT'))

Related

SQL query statement Self Join?

new to SQL.
I have the following set of data
A X Y Z
1 Wind 1 1
2 Wind 2 1
3 Hail 1 1
4 Flood 1 1
4 Rain 1 1
4 Fire 1 1
I would like to select all distinct 'A' fields where for all rows that contain A have flood and rain.
So in this example, the query would return only the number 4 since for the set of all rows that contain A = 4 we have Flood and Rain.
I need the values of A where for a given value 'a' in A, there exists rows with 'a' that must contain all of the following fields provided (in the example Flood and Rain).
Please let me know if you need further clarification.
I need the values of A where for a given value 'a' in A, there exists rows with 'a' that must contain all of the following fields provided (in the example Flood and Rain).
You can use aggregation, and filter with a having clause:
select a
from mytable t
where x in ('Flood', 'Rain') -- either one or the other
having count(*) = 2 -- both match
If tuples (a, x) tuples are not unique, then you want having count(distinct x) = 2 instead.
You Shooud use count(distinct X) group by A and having
count(distinct...) avoid situation where you have two time the same value for X
select A
from my_table
WHERE x in ('Flood', 'Rain')
group A
having count(distinct X) = 2

Select row if multiple present values are present in another table

I'm doing a search function on a movie database, I want to give the option to search a film with two genres (ie: crime id:6 and adventure id:7)
I basically want to get a row from title if it has genre_id 6 AND 7 present in the title_genre value. Obviously, this query below isn't working (I understand why it's not but I don't know how to fix it).
Any help please?
SELECT * FROM (`title`, `title_genre`)
WHERE `title`.`active` = 1
AND `title`.`media_id` = title_genre.media_id
AND title_genre.genre_id = 6 AND title_genre.genre_id = 7
You can use the exists to check the existence of other genre_id = 7 in title_genre and also using explicit join makes it much better as
select
t.*,
tg.*
from title t
join title_genre tg on tg.media_id = t.media_id
where
tg.genre_id = 6
and exists(
select 1 from title_genre tg1
where tg1.media_id = t.media_id
and tg1.genre_id = 7
)

mysql select while skipping some number of rows

Is there a mysql syntax that can hop some rows?
For example
id value
1 a
2 b
3 c
4 d
5 e
6 f
7 g
8 h
9 i
SELECT * FROM table HOP BY 2
so the result will be
id value
3 c
6 f
9 i
or
id value
1 a
4 d
7 g
Take note: We don't know the actual ID of a row so we can't use a WHERE clause like this
WHERE ID is a multiple of 3 or etc.
I didn't realize you could do math in sql queries. Learned something new. Cool. Here's code that would select 1, 4, and 7.
$stmt = mysqli_prepare($connection, "SELECT * FROM users WHERE (ID+2)%3 = 0 AND ID>1");
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
while($row = mysqli_fetch_assoc($result)){
echo $row['username'];
}
I don't see why it wouldn't work if id has gaps, as the man with ?mandarin? symbols for a name said.
Modulus(%), if you don't know, gives the number of decimals given by a division problem. So 3/3=1, with no decimals, so 3%3=0, whereas 4/3=1.333333..., so 4/3 equals infinity(not really in programming, but close enough).
SELECT * FROM hoptable WHERE ID%3 =0 AND ID>1
SET #row_idx := 0;
SELECT *, (#row_idx := #row_idx + 1) AS idx
FROM table
HAVING idx % 3 = 0;
You probably want to include an ORDER BY clause so the row index can actually be meaningful though. You can't rely on the result being ordered by id without specifying it.

how to search for a given sequence of rows within a table in SQL Server 2008

The problem:
We have a number of entries within a table but we are only interested in the ones that appear in a given sequence. For example we are looking for three specific "GFTitle" entries ('Pearson Grafton','Woolworths (P and O)','QRX - Brisbane'), however they have to appear in a particular order to be considered a valid route. (See image below)
RowNum GFTitle
------------------------------
1 Pearson Grafton
2 Woolworths (P and O)
3 QRX - Brisbane
4 Pearson Grafton
5 Woolworths (P and O)
6 Pearson Grafton
7 QRX - Brisbane
8 Pearson Grafton
9 Pearson Grafton
So rows (1,2,3) satisfy this rule but rows (4,5,6) don't even though the first two entries (4,5) do.
I am sure there is a way to do this via CTE's but some help would be great.
Cheers
This is very simple using even good old tools :-) Try this quick-and-dirty solution, assuming your table name is GFTitles and RowNumber values are sequential:
SELECT a.[RowNum]
,a.[GFTitle]
,b.[GFTitle]
,c.[GFTitle]
FROM [dbo].[GFTitles] as a
join [dbo].[GFTitles] as b on b.RowNumber = a.RowNumber + 1
join [dbo].[GFTitles] as c on c.RowNumber = a.RowNumber + 2
WHERE a.[GFTitle] = 'Pearson Grafton' and
b.[GFTitle] = 'Woolworths (P and O)' and
c.[GFTitle] = 'QRX - Brisbane'
Assuming RowNum has neither duplicates nor gaps, you could try the following method.
Assign row numbers to the sought sequence's items and join the row set to your table on GFTitle.
For every match, calculate the difference between your table's row number and that of the sequence. If there's a matching sequence in your table, the corresponding rows' RowNum differences will be identical.
Count the rows per difference and return only those where the count matches the number of sequence items.
Here's a query that implements the above logic:
WITH SoughtSequence AS (
SELECT *
FROM (
VALUES
(1, 'Pearson Grafton'),
(2, 'Woolworths (P and O)'),
(3, 'QRX - Brisbane')
) x (RowNum, GFTitle)
)
, joined AS (
SELECT
t.*,
SequenceLength = COUNT(*) OVER (PARTITION BY t.RowNum - ss.RowNum)
FROM atable t
INNER JOIN SoughtSequence ss
ON t.GFTitle = ss.GFTitle
)
SELECT
RowNum,
GFTitle
FROM joined
WHERE SequenceLength = (SELECT COUNT(*) FROM SoughtSequence)
;
You can try it at SQL Fiddle too.

Oracle/MYSQL: Sort records from a select query on a column that contains alphanumeric values

I know that this question has been asked in various forms but my requirement happens to be a bit different.
Suppose I have a table that contains data as follows:
ID NAME VALUE
-----------------------------
1 ABC-2-2 X
2 PQRS-1-3 Y
3 ABC-3-2 Z
4 PQRS-1-4 A
5 PQRS-3-4 B
6 MNO-2-1 C
7 AAA-1 D
8 BBB-2 E
9 CCC-3 F
Now, the output that I'm expecting should look something like this:
ID NAME VALUE
-----------------------------
7 AAA-1 D
2 PQRS-1-3 Y
4 PQRS-1-4 A
8 BBB-2 E
6 MNO-2-1 C
1 ABC-2-2 X
9 CCC-3 F
3 ABC-3-2 Z
5 PQRS-3-4 B
Note that this is not a direct alpha-numeric sort. Instead, the value before the first "-" is ignored and the fields are sorted on what is after the first "-" in the name.
I'm not very familiar with PL/SQL and any kind of help on this would be appreciated.
Thanks.
PS: Note that this should work on both Oracle and MySQL.
For your example this would suffice (Oracle syntax):
ORDER BY SUBSTR(name,4)
If the number of characters before the first hyphen can vary, you can do this (again Oracle syntax):
ORDER BY SUBSTR(name,INSTR(name,'-')+1)
However that won't work if you have codes like:
AAA-10-1
AAA-8-1
AAA-9-1
and expect AAA-10-1 to appear after AAA-9-1. Then you will need to parse it further:
ORDER BY LPAD(SUBSTR(name,INSTR(name,'-')+1, INSTR(name,'-',1,2)-INSTR(name,'-')-1),10,'0'),
LPAD(SUBSTR(name,INSTR(name,'-',1,2)+1),10,'0')
(NB I have used LPAD(x,10,'0') to turn a value like '1' into '0000000001' and so on, rather than use TO_NUMBER since this could fail if there are any non-numerics in your data.)
Example:
with data as
(
select 'AAA-1' name from dual
union all
select 'PQR-1-4' name from dual
union all
select 'PQR-1-3' name from dual
union all
select 'AAA-10-10' name from dual
union all
select 'AAA-10-1' name from dual
union all
select 'AAA-9-10' name from dual
union all
select 'AAA-9-1' name from dual
)
select *
from data
ORDER BY LPAD(SUBSTR(name,INSTR(name,'-')+1, INSTR(name,'-',1,2)-INSTR(name,'-')-1),10,'0'),
LPAD(SUBSTR(name,INSTR(name,'-',1,2)+1),10,'0');
Output:
NAME
---------
PQR-1-3
PQR-1-4
AAA-9-1
AAA-9-10
AAA-10-1
AAA-10-10
AAA-1
And if AAA-1 should come first:
ORDER BY LPAD(SUBSTR(name,INSTR(name,'-')+1, INSTR(name||'-','-',1,2)-INSTR(name,'-')-1),10,'0'),
LPAD(SUBSTR(name,INSTR(name||'-','-',1,2)+1),10,'0') nulls first
Not sure about mysql syntax, but you can do this in oracle:
select * from <your_table>
order by substr(name, 5)
in mssql the syntax of finding your problem is :
select * from mytable order by substring(name,PATINDEX('%-%',name)+1,len(name)-PATINDEX('%-%',name))
SqlFiddle