select statement from 2 unrelated tables - mysql

There's 2 unconnected tables, with no common IDs
+---------------------+
| names |
+------+--------------+
| name | lastN |
+-------------+-------+
| Anthony | monta |
| Ryo | shizu |
+------+--------------+
+----------------------+
| nicknames |
+------+---------------+
| nickname |
+------+---------------+
| miso_hungry |
+------+---------------+
I'm trying to run a select query on both tables and currently doing something like:
SELECT names.name, nicknames.nickname
FROM names, nicknames
WHERE names.name="miso_hungry" OR nicknames.nickname="miso_hungry"
I'm getting back a weird results with repeating identical rows, which doesn't make sense.
For example if I search for miso_hungry with the query above it will return every row of "names" table for some reason and append the correct rows from the "nicknames" table..
Attaching a screenshot of the results
Above should show "NULL" under name column, since "miso_hungry" is not found in that column and I'm not sure why it prints every row of the "names" table also.

You can use UNION Clause
Each SELECT statement within UNION must have the same number of columns
The columns must also have similar data types
The columns in each SELECT statement must also be in the same order
So we need to made them satisfy above condition. We can use Aliasing to do this.
SELECT name,(SELECT NULL) as nickname FROM names WHERE name = "miso_hungry"
UNION
SELECT (SELECT NULL) as name, nickname FROM nicknames WHERE nickname = "miso_hungry"
Edited
If you want to get the match count from both table use query like below :
SELECT SUM(count) as count FROM (
SELECT count(*) as count FROM names WHERE name = "miso_hungry"
UNION ALL
SELECT count(*) as count FROM nicknames WHERE nickname = "miso_hungry"
) both_table

The order of execution in your statement is from,where,select. With and implicit join you get a cartesian product which given
use sandbox;
create table n(name varchar(20));
create table nn(nickname varchar(20));
insert into n values('Antony'),('Ryo');
insert into nn values('miso');
results in
MariaDB [sandbox]> SELECT n.name, nn.nickname
-> FROM n, nn;
+--------+----------+
| name | nickname |
+--------+----------+
| Antony | miso |
| Ryo | miso |
+--------+----------+
2 rows in set (0.00 sec)
The where clause is then applied - which yields the same result.

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 Query results

Table name : Students.
The Table i have:
mysql> SELECT * from Students;
+-----------+-------------+-------+
| Rollno | Name | Marks |
+-----------+-------------+-------+
| 251602122 | Sumit Tyagi | 70 |
| 251602121 | parveen | 90 |
+-----------+-------------+-------+
Following query returns the following result even 8 is not a attribute.
mysql> select 8 from Students;
+---+
| 8 |
+---+
| 8 |
| 8 |
+---+
Similarly
mysql> SELECT 'some_string' from Students;
+-------------+
| some_string |
+-------------+
| some_string |
| some_string |
I just want to know why this happens.
The query returns one line for every record in your table.
But you don't select data from those record. You just select the number 8 for each line. And this gets returned.
Select statement looks for column name in a table. You can make sure SQL look for a column name in a table by using TableName.ColumnName.
In the example you wrote, you are asking for a constant or hardcoded value 8/some_string to be returned from the table which is not the column name. So it will return the hardcoded or constant value you asked for, the number of times equal to number of rows in your table.
If you want to make sure it look for the column name, use the syntax I mentioned as TableName.ColumnName. You can also provide an alias for your table. So in the example above, if you use the syntax as
SELECT Students.8 from Students;
or
SELECT s.8 FROM Students s;
It will look for column name as 8 instead of constant or hardcoded value 8.
If I am not wrong, it is a best practice to use TableName.ColumnName or alias.ColumnName while writing queries as it checks for column name in that particular table.

Add user defined value to a column in an sql query

I have an SQL query:
select DISTINCT shortname_chn from dim_channel;
The query returns me data for example:
| shortname_chn (VARCHAR) |
|__________________________|
| MTV |
| National Geographic|
| Discovery |
| ARY News |
How can I manipulate the SQL query so that I can add an additional row to the returned rows.
Following is the result I wish to get after running some query:
| shortname_chn (VARCHAR) |
|__________________________|
| MTV |
| National Geographic|
| Discovery |
| ARY News |
| ALL |
Where the last row "ALL" is user defined, not present in the database.
In the above mentioned regard, I researched and came across this question : How to add a user defined column with a single value to a SQL query but it targets the problem of adding a whole new column.
select DISTINCT shortname_chn from dim_channel
UNION
SELECT 'ALL'
You can simply do something like this by UNIONing with a query that returns your fake row, e.g.:
SELECT DISTINCT
shortname_chn
FROM dim_channel
UNION ALL
SELECT 'ALL' AS shortname_chn

Retrieve rows in which a column doesn't contain a value

I have a MySQL table like below:
| ID | userIDs
---------------
| 1 | 4,3,5
| 2 | 2,3
| 3 | 1,2,3
I want to retrieve all the rows in which userIDs doesn't contain 1.
I tried
SELECT * FROM tablename WHERE 1 NOT IN (userIDs)
But it's not working.
Use FIND_IN_SET
SELECT * FROM tablename
WHERE find_in_set(1, userIDs) = 0
But actually you should rather change your table design. Never store multiple values in a single column!

filter sql rows using update statement

I am trying to write a query which can get invalid refby(is related to id), please check following db structure...
| id | acnumber | refby |
+----+-----------+--------+
| 1 | ac01 | 2 |
+----+-----------+--------+
| 2 | ac02 | 1 |
+----+-----------+--------+
| 3 | ac03 | 5 |
+----+-----------+--------+
As you can find there is no id with value of 5 in above table so query must return 3rd row as result.
I have tried...
SELECT * FROM tbl.members WHERE refby != (SELECT id FROM tbl.members WHERE id = refby)
But this is not giving correct results, please help, thanks.
SELECT * FROM members WHERE refby not in (SELECT id FROM members)
This should solve your problem
You can try this using not in:-
SELECT * FROM tbl.members WHERE refby not in (SELECT id FROM members)
This should be a LEFT JOIN, NOT IN is slow on large tables... assuming id and refid is an PRIMARY KEY or UNIQUE key (read unique within your dataset) then this query should return the same results.
SELECT
*
FROM
members members1
LEFT JOIN
members members2
ON members1.id = members2.refby
WHERE members2.id IS NULL
check the sqlfriddle http://sqlfiddle.com/#!2/05731/1