I have a table in MySql and table name is logs
+---------------+---------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+---------------+---------------+------+-----+---------+-------+
| domain | varchar(50) | YES | MUL | NULL | |
| sid | varchar(100) | YES | MUL | NULL | |
| email | varchar(100) | YES | MUL | NULL | |
+---------------+---------------+------+-----+---------+-------+
The following are sample rows from the table
+------------+----------------+---------------
| sid | email | domain|
+------------------------------------+-------+
| 1 | | [email protected] | xxx |
| 2 | | [email protected] | xxx |
| 2 | | [email protected] | yyy |
| 2 | | [email protected] | yyy |
| 3 | | [email protected] | zzz |
| 4 | | [email protected] | qqq |
| 2 | | [email protected] | ppp |
+---+--------+-----------------------+-------+
I want a query something like
select * from logs
where sid IN (select sid from logs
where domain="xxx" AND email="[email protected]")
Desired output
+------------+-----------------------+--------
| sid | email | domain|
+------------------------------------+-------+
| 1 | | [email protected] | xxx |
| 2 | | [email protected]oo.com | xxx |
| 2 | | [email protected] | yyy |
| 2 | | [email protected] | yyy |
| 2 | | [email protected] | ppp |
+---+--------+-----------------------+-------+
I can do it using joins but is there any way to get results without using joins or any optimized version of this query
The following recommendations will help you in your SQL tuning process.
You'll find 3 sections below:
ALTER TABLE `logs` ADD INDEX `logs_idx_sid_domain_email_com` (`sid`,`domain`,`email`,`com`);
SELECT
*
FROM
logs
WHERE
EXISTS (
SELECT
1
FROM
logs AS logs1
WHERE
(
logs1.domain = 'xxx'
AND logs1.email = logs1."[email protected]"
)
AND (
logs.sid = logs1.sid
)
)