Query where row contains a variable's data - mysql

Probably easy but I've searched high and low for the answer with no joy.
Say I have this data in a table called 'brand'
---------------------------------------
ID | brand_name | brand_image |
---------------------------------------
1 | Sony | sonypic |
---------------------------------------
2 | Samsung | samsungpic |
---------------------------------------
3 | Panasonic | panapic |
---------------------------------------
I want to select the row from the table where the 'brand_name' appears at the beginning of a variable.
eg. $variable = Sony Walkman
I've done a million queries checking to see if a variable is in a column but never done one checking for a column in a variable. Is it possible?

Assuming you will use prepared statement:
SELECT * FROM brand WHERE ? LIKE CONCAT(brand_name, '%')

You can use LIKE. Just snip out the first bit you want to look for:
SELECT * FROM brands WHERE brand_name LIKE CONCAT(brand_name, '%')

Do you mean
select * from brand where brand_image like concat(brand_name, '%')
?

Related

How to run alternative where condition if row is zero

Suppose i have a table
table
+-------------+
| id | name |
+-------------+
| 1 | xabx |
| 2 | abxd |
| 3 | axcd |
| 4 | azyx |
| 5 | atyl |
| 6 | aksd |
| 7 | baabc|
| 8 | aabcd|
+-------------+
first i have to get data if matches first some char like :
if name = aab
then have to run select * from table where name like 'aab%'
then it returns
+-------------+
| 8 | aabcd |
+-------------+
which execatlly i want
but if i have only abc
then the above query return 0 row
then i have to search from middle like :
select * from table where name like '%abc%'
then it returns which is the alternative
+-------------+
| 7 | baabc|
| 8 | aabcd|
+-------------+
i have no much knowledge about mysql is there any query which can do like if first where condition don't have row then run alternative where condition
i have tried this but didn't work as i want.
select * from table where name like 'abc%' or name like '%abc%'
fiddle
thanks in advance
This is somewhat your desired result:
select *from t
where (case
when name like 'abc' then 1
when name like 'bc%' then 1
when name like '%bc' then 1
when name like '%bc%' then 1
else null
end)
order by name
limit 1;
I just put all the combinations as conditions.
You can interchange their sequence or remove unnecessary condition.
limit 1 makes only 1 row visible for whichever condition satisfies.
Here is the answer from your fiddle. Check it out
Hope it helps!
This is a possible solution:
Left joining the table on itself, where the table is initially filtered by the more inclusive %bx% and then the join is filtered by the more restrictive bx%.
This allows you to use the joined name if it exists, but revert to the original if not:
SELECT t1.id, IF(t2.name IS NULL, t1.name, t2.name) name
FROM test t1
LEFT JOIN test t2 ON t2.id = t1.id AND t1.name like 'bx%'
WHERE t1.name LIKE '%bx%'
This may/may not be ideal depending on the size or your dataset.
COUNT checking may work
select *
from table
where name like 'aab%' or
((select count(*) from table where name like 'aab%') = 0 and name like '%abc%')
I guess that it would be a good idea to compute the count value into a variable first, however, the optimizer may recognize independent subquery anyway and run it once.

mysql select from 2 other columns in the same table

I have a table which looks like this but much longer...
| CategoryID | Category | ParentCategoryID |
+------------+----------+------------------+
| 23 | Screws | 3 |
| 3 | Packs | 0 |
I am aiming to retrieve one column from this which in this instance would give me the following...
| Category |
+--------------+
| Packs/Screws |
Please excuse me for not knowing exactly how to word this, so far I can only think to split the whole table into multiple tables and use LEFT JOIN, this seems like a very good opportunity for a learning curve however.
I realise that CONCAT() will come into play when combining the two retrieved Category names but beyond that I am stumped.
SELECT CONCAT(x.category,'/',y.category) Category
FROM my_table x
JOIN my_table y
ON y.categoryid = x.parentcategoryid
[WHERE x.parentcategoryid = 0]

How to optimize search in list in SQL

I have to make a SQL query in Mysql to search a string list (for ex: 1,2,3) in a columns (for ex: list_id), which also have string value list (1,2,3).
For more detail, my_table is
+-----------+----------+
| id | list_id |
+-----------+----------+
| 1 | 29 |
| 2 | 30 |
| 3 | 31 |
| 4 | 4,5,6,7 |
| 5 | 8,9,10,11|
| 6 | 4,5,8,9 |
| 7 | 1,2,3,6 |
+-----------+----------+
The search value is 1,5,8 and I need get the rows have list_id have 1 or 5 or 8 in it's list. Therefore, the result wil be:
+-----------+----------+
| id | list_id |
+-----------+----------+
| 4 | 4,5,6,7 |
| 5 | 8,9,10,11|
| 6 | 4,5,8,9 |
| 7 | 1,2,3,6 |
+-----------+----------+
My query string is:
SELECT * FROM my_table
WHERE list_id LIKE '%,1,%'
OR list_id LIKE '1,%'
OR list_id LIKE '%,1'
OR list_id LIKE '%,5,%'
OR list_id LIKE '5,%'
OR list_id LIKE '%,5'
OR list_id LIKE '%,8,%'
OR list_id LIKE '8,%'
OR list_id LIKE '%,8'
It is match correct what I want. However, the length of query is in proportion to length of list.
Does REGEXP is better than LIKE in this circumstance?
Does anyone have experience to make another solution better?
You may try to concatenate commas to your field (or use SET in MySQL or make a better database structure - in which you join on tables in which the related data is stored).
SELECT * FROM yourtable WHERE CONCAT(',', fieldname, ',') like '%,1,%';
Yes, regular expressions will work for this. Here is what you can do:
SELECT * FROM junk
WHERE CONCAT(',', list_id, ',') REGEXP CONCAT(',(', REPLACE('1,3,8',',','|'), '),');
Results:
ID | LIST_ID
5 | 8,9,10,11
6 | 4,5,8,9
7 | 1,2,3,6
Please see SQL Fiddle demo here.
We turn the query list 1,3,8 into an alternating group 1|3|8. You might be able to do this in your application code to avoid using the REPLACE() function above.
UPDATE Apologies, I mistakenly used 1,3,8 as the query parameter instead of 1,5,8. But it should still work.
I am going to strongly suggest that you change the design of the database (I am assuming you have some control or influence over it).
You should make the id column non-unique and then the list_id column should contain a single value. You can then search as follows:
SELECT id WHERE list_id IN (1,5,8)
If it is a big table and there are a lot of list_id values, put an index on the list_id column.
If you need the output in a comma-separated list, then you will need to use an aggregating concatenation function with GROUP BY (e.g., GROUP_CONCAT() in MySQL).
If you cannot change the design of the schema, then use one of the other suggestions here.

Compare a value from a CSV column in mysql with more checks

I need to have a query which has two parts.
I mean two where clause.
till now I have reached to the following, but it dosen't work properly.
SELECT * from items
where
FIND_IN_SET( '3', category_id )
AND postcode LIKE 'sw19%'
order by id
this query only runs the first part, i.e., the FIND_IN_SET() part. and just ignores the second part i.e., Postcode check...
I want to know is there a solution for this kind of query.
DETAILS
I want to compare the values from 2 columns:
1 column is a csv column , eg. 1,2,3,4,5
the other is postcode B17 SW19 etc
Table is like the following.
---+------+-------------+----------+-
id | item | category_id | postcode |
---+------+-------------+----------+-
1 | abc | 1,2,3,4 | SW19 |
---+------+-------------+----------+-
2 | def | 3,4,5 | NW6 |
---+------+-------------+----------+-
3 | xyz | 6,7,8,9 | SW19 |
---+------+-------------+----------+-
4 | ghi | 8,9,10,11 | SW19 |
---+------+-------------+----------+-
etc.
if I want to select an entry whose category_id contains '3' AND whose postcode starts from 'SW', what query will it be?
I just found out the solution which completely resolves my problem and though it would help someone in future.
Well, the query goes like this:
Select * from table_name where FIND_IN_SET('3', category_id) >0 AND postcode LIKE 'sw%'
Regards,
Shoaib.
:) Just simple query for this
SELECT * FROM tablename1 WHERE category_id LIKE '%,3,%' AND postcode LIKE 'SW%'

MySQL - COUNT before INSERT in one query

Hey all, I am looking for a way to query my database table only once in order to add an item and also to check what last item count was so that i can use the next number.
strSQL = "SELECT * FROM productr"
After that code above, i add a few product values to a record like so:
ID | Product | Price | Description | Qty | DateSold | gcCode
--------------------------------------------------------------------------
5 | The Name 1 | 5.22 | Description 1 | 2 | 09/15/10 | na
6 | The Name 2 | 15.55 | Description 2 | 1 | 09/15/10 | 05648755
7 | The Name 3 | 1.10 | Description 3 | 1 | 09/15/10 | na
8 | The Name 4 | 0.24 | Description 4 | 21 | 09/15/10 | 658140
i need to count how many times it sees gcCode <> 'na' so that i can add a 1 so it will be unique. Currently i do not know how to do this without opening another database inside this one and doing something like this:
strSQL2 = "SELECT COUNT(gcCode) as gcCount FROM productr WHERE gcCode <> 'na'
But like i said above, i do not want to have to open another database query just to get a count.
Any help would be great! Thanks! :o)
There's no need to do everything in one query. If you're using InnoDB as a storage engine, you could wrap your COUNT query and your INSERT command in a single transaction to guarantee atomicity.
In addition, you should probably use NULL instead of na for fields with unknown or missing values.
They're two queries; one is a subset of the other which means getting what you want in a single query will be a hack I don't recommend:
SELECT p.*,
(SELECT COUNT(*)
FROM PRODUCTR
WHERE gccode != 'na') AS gcCount
FROM PRODUCTR p
This will return all the rows, as it did previously. But it will include an additional column, repeating the gcCount value for every row returned. It works, but it's redundant data...