How to fetch rows - mysql

I'm trying to extract rows from database depending on two columns where only one column is indexed (primary key) and other is not .
Example : table A has columns a(PK), b(date feild), c
Now I'm trying to get rows where b = 29-04-2019 and a = 1 , b = 30-04-2019 and a = 2 . In this case i can only get 4 rows 2 rows for a = 1 (both dates) and two rows for a = 2 (both dates) but I need only two rows totally .
I have tried this Query :
select * from A
where a in (1,2)
and b in ("2019-04-29","2019-04-30")

You need the SELECT using WHERE with OR operator.
Typical example is:
SELECT * FROM table_name
WHERE condition1
OR condition2;
This will select all matching rows where EITHER condition1 is true, OR condition2 is true.
So in your case:
condition1 is a = 1 AND b = "2019-04-29"
condition2 is a = 2 AND b = "2019-04-30"
Putting it together:
SELECT * from A
WHERE (a = 1 AND b = "2019-04-29")
OR (a = 2 AND b = "2019-04-30")
Note that if you data has more than 1 instance of each condition, you will return more than 2 rows in total.

Related

Avoid duplicates on MySQL update

I have a many-to-many relation table like this
element_a
element_b
1
2
1
3
2
1
2
3
3
1
3
3
I want to replace element_a with id 2 by id 1
UPDATE mytable x
SET x.element_a = 1
WHERE x.element_a = 2;
Since there is an unique index on (element_a, element_b ), this will result with duplicates error.
How can I execute my query without MySQL Error 1062 ?
You can use an update with LEFT JOIN:
UPDATE mytable x
LEFT JOIN mytable t ON t.element_b = x.element_b AND 1 = t.element_a
SET x.element_a = 1
WHERE
x.element_a = 2 AND t.element_a IS NULL
If t.element_a IS NOT NULL then pair element_a, element_b already exists in your table. Thus adding t.element_a IS NULL in the WHERE clause prevents UPDATE in case of duplicates.
Demo here

SELECT where with multiple conditions in ONE query

There are two things I want to achieve.
This is my database table called "table".
id | friend
---|--------
1 | null
2 | 1
3 | 0
4 | 3
5 | 3
6 | null
There are two SELECT queries I want to do.
$id = 3;
SELECT * FROM table WHERE id = $id; // Not sql injection safe, just an example
This should select row id = 3. If that row's friend column = 0, then:
SELECT rows WHERE friend = $id.
If that row's friend column is something other than 0, then just return that row, row 3. But since my table above shows that row id 3's friend column = 0, this should altogether return rows: 3, 4, 5.
Also, another scenario a something a little different:
$id = 5;
SELECT * FROM table WHERE id = $id;
If that row's friend column <> (does NOT equal) 0 AND IS NOT NULL, then use the friend number and:
SELECT * WHERE id = friend from previous table.
In this example, it will return rows 3, 4, 5 because ID = 5 and the friend ID of 5 is 3. So we search columns id AND friend for 3 and we select it.
I want to combine all of those together into one MySQL SELECT query. How can I do that?
Any help will be appreciated!
In the first scenario, I don't understand exactly why a zero value for friend returns 3, 4, and 5. Why not 2? I'm assuming that if the friend value is zero, then add the rows which have you as a friend.
So, before this first example, I cannot stand a table named "table", so I will use friends as the name of the table.
SELECT FF.id
FROM friends FF
INNER JOIN friends FID on FF.friend = FID.id
WHERE FID.friend = 0 AND FID = $id
UNION
SELECT F2.id FROM friends F2 WHERE F2.id = $id AND F2.friend IS NOT NULL
The inner join, takes the id of friends (FID.id) and joins on the the friends table again to get all the records with that as a friend (FF.friend) value.
Then UNION will include the original id. Both sides of the UNION will return no results if the friend field is NULL.
Similarly for the second scenario, use the given value, ($id = 5), find that record's friend value, and query for all records with that as a friend, then union its record.
SELECT FF.id
FROM friends FF
WHERE FF.friend = (SELECT FIN.friend FROM friends FIN where FIN.id = $id)
UNION
SELECT FIN.friend FROM friends FIN where FIN.id = $id

MySQL - select product_id from 2 different tables and group results

situation:
table 1 - #__virtuemart_products
virtuemart_product_id | product_special
PRODUCTS_IDS | 0 or 1
table 2 - #__virtuemart_product_badges
virtuemart_product_id | product_badge
PRODUCTS_IDS | for this situation code 3
I have a default SQL
SELECT p.`virtuemart_product_id`
FROM `#__virtuemart_products` as p
WHERE p.`product_special` = 1;
results is product IDs like 2,3,225,...
I need modify this SQL syntax for select IDs from 2 different tables and return one column.
If I modify syntax like that:
SELECT p.`virtuemart_product_id`, badges_table.`virtuemart_product_id`
FROM `#__virtuemart_products` as p, `#__virtuemart_product_badges` as badges_table
WHERE p.`product_special` = 1 OR badges_table.`badge` = 3
Result is:
virtuemart_product_id | virtuemart_product_id
1 | 123
1 | 321
1 | 231
....
why is first column 1,1,1,...? here must be product_id, no product_special code
I need group this results into one column virtuemart_product_id
What I doing wrong?
I think what you are looking for is UNION of the IDs fetched from two different tables.
SELECT p.`virtuemart_product_id`, badges_table.`virtuemart_product_id`
FROM `#__virtuemart_products` as p, `#__virtuemart_product_badges` as
badges_table
WHERE p.`product_special` = 1 OR badges_table.`badge` = 3
What the above query is doing is, it is performing a join between the two tables with the condition that product_special should be 1 or badge should be 3. Hence, each row from one table will be joined with each row of the other table where the condition will satisfy.
To get IDs from both the tables you can get the results from each table according to condition and then perform a UNION on them. So for example
(SELECT `virtuemart_product_id` FROM `#__virtuemart_products` WHERE
`product_special` = 1)
UNION
(SELECT `virtuemart_product_id` FROM
`#__virtuemart_product_badges` WHERE `badge` = 3)
I hope this helps.

Conditional condition in ON clause

I am trying to apply a conditional condition inside ON clause of a LEFT JOIN. What I am trying to achieve is somewhat like this:
Pseudo Code
SELECT * FROM item AS i
LEFT JOIN sales AS s ON i.sku = s.item_no
AND (some condition)
AND (
IF (s.type = 0 AND s.code = 'me')
ELSEIF (s.type = 1 AND s.code = 'my-group')
ELSEIF (s.type = 2)
)
I want the query to return the row, if it matches any one of the conditions (Edit: and if it matches one, should omit the rest for the same item).
Sample Data
Sales
item_no | type | code | price
1 0 me 10
1 1 my-group 12
1 2 14
2 1 my-group 20
2 2 22
3 2 30
4 0 not-me 40
I want the query to return
item_no | type | code | price
1 0 me 10
2 1 my-group 20
3 2 30
Edit: The sales is table is used to apply special prices for individual users, user groups, and/or all users.
if type = 0, code contains username. (for a single user)
if type = 1, code contains user-group. (for users in a group)
if type = 2, code contains empty-string (for all users).
Use the following SQL (assumed, the the table sales has a unique id field as usual in yii):
SELECT * FROM item AS i
LEFT JOIN sales AS s ON i.sku = s.item_no
AND id = (
SELECT id FROM sales
WHERE item_no = i.sku
AND (type = 0 AND code = 'me' OR
type = 1 AND code = 'my-group' OR
type = 2)
ORDER BY type
LIMIT 1
)
Try following -
SELECT *,SUBSTRING_INDEX(GROUP_CONCAT(s.type ORDER BY s.type),','1) AS `type`, SUBSTRING_INDEX(GROUP_CONCAT(s.code ORDER BY s.type),','1) AS `code`,SUBSTRING_INDEX(GROUP_CONCAT(s.price ORDER BY s.type),','1) AS `price`
FROM item AS i
LEFT JOIN sales AS s
ON i.sku = s.item_no AND (SOME CONDITION)
GROUP BY i.sku

mysql select twice itself again in one table

How to select in 1 query below. This query need re search that's find value to their own loop.
This is different from other sub query , using 1 table only
TAble T
| num| WHOSE
| 1 | A
| 1 | C
| 2 | B
| 2 | C
| 3 | D
Criteria to match records (conditions):
The value in column whose is not C
The value in column num does not match a value for another record in condition 1.
I want to find the record the value 3 in column num (which has D for column whose).
select * from T where whose <> C and ( num is not one of c's)
1 A can not because C has 1
2 B can not because C has 2
3 D is what I want, because it doesn't have C in column whose nor share a value in column num with a record that does have C in the column whose.
First select num of those records where whose is C. Then select those records where whose is not C and also where num is not one of the ones in subquery.
Select * from T where whose <> 'C' and num not in (Select Num from T where whose = 'C' )
Another way to achieve the same result is with a LEFT JOIN on the same table:
SELECT T.*
FROM T
LEFT JOIN T t2 on t2.num = T.num and t2.whose = 'C'
WHERE T.whose <> 'C' AND t2.whose IS NULL
Check it out on this SQL Fiddle, where the result is:
| num | whose |
| 3 | D |
Additionally, a similar way to write the query is to use the NOT EXISTS clause in the WHERE conditions, like this:
SELECT T.* from T
WHERE T.whose <> 'C' AND NOT EXISTS (SELECT 1 FROM T t2 WHERE
t2.num = T.num AND t2.whose = 'C')
Check it out in this SQL fiddle.
To read more about the comparison between EXISTS and LEFT JOIN see this article. In the summary at the end it has the following conclusions:
MySQL can optimize all three methods to do a sort of NESTED LOOPS ANTI JOIN.
...
However, these three methods generate three different plans which are executed by three different pieces of code. The code that executes EXISTS predicate is about 30% less efficient than those that execute index_subquery and LEFT JOIN optimized to use Not exists method.
That's why the best way to search for missing values in MySQL is using a LEFT JOIN / IS NULL or NOT IN rather than NOT EXISTS.