I am currently working on a user system, and would like to setup multiple usergroups/ranks per member. I see other posts on here explaining it by using foreign keys, denormalized tables, etc... but they're all from 2010-2012, so wasn't sure if there were easier/better standard ways of doing it.
CREATE TABLE IF NOT EXISTS `users` (
`id` int(10) NOT NULL AUTO_INCREMENT,
`username` varchar(50) NOT NULL,
`password` varchar(80) NOT NULL,
`email` varchar(80) NOT NULL,
`character_name` varchar(50) NOT NULL,
`verify` int(5) NOT NULL,
`rank` varchar(50) NOT NULL,
`position` int(10) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE INDEX (`email`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=3;
CREATE TABLE IF NOT EXISTS `rank` (
`id` int(10) NOT NULL AUTO_INCREMENT,
`rank` varchar(50) NOT NULL,
`position` int(10) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=26 ;
The above are my two tables. Here are the two table structures with three examples in each:
users
id | username | password | email | character_name | verify | rank | position
1 | userA | passA | A#A | characterA | yes | mem | 1
2 | userB | passB | B#B | characterB | yes | mod | 1
3 | userC | passC | C#C | characterC | yes | adm | 3
rank
id | rank | position
1 | mem | 1
2 | mod | 1
3 | adm | 3
Users should be able to be in multiple ranks.
userA should only be a mem.
userB should be a mem and mod.
userC should be a mem, mod, and adm.
If I were to join both tables:
SELECT * FROM rank INNER JOIN users ON rank.position = users.position;
Would that cause userA to be mem and mod as well, since the position for both is 1?
Would it make more sense to remove rank and position from users, position from rank, and join based on user id?
For example (question 2):
users
id | username | password | email | character_name | verify
1 | userA | passA | A#A | characterA | yes
2 | userB | passB | B#B | characterB | yes
3 | userC | passC | C#C | characterC | yes
rank
id | rank
1 | mem
2 | mem
2 | mod
3 | mem
3 | mod
3 | adm
SELECT * FROM rank INNER JOIN users ON rank.id = users.id;
Once selected, I want certain ranks to be able to do certain things.
$sql = SELECT * FROM rank INNER JOIN users ON rank.id = users.id;
$ranks = $conn->query($sql);
$ranks->execute();
foreach ($ranks as $row) {
if($row['rank'] == "mem" {
Do something.
}
if($row['rank'] == "mod" {
Do something else.
}
if($row['rank'] == "adm" {
Do another something else.
}
}
Is the above correct?
Edited, because my first posting apparently wasn't clear enough.
Can anyone help?
Related
I have a person table and a score table. The Person table basically stores a person's information while score table stores what kind of score a person has. I set the FK constraint in score table to ON DELETE: CASCADE
person
- id
- name
- scored_id (FK)
score
- id (PK)
- bmi
- weight
So, in the table setting score.id is linked with person's scored_id. That being said when I delete a record in score, a person will get deleted as well. But why when I delete a record in person, the record of his in score is not deleted?
Just an idea how you might structure the tables and use a foreign key which will delete records from the score table if/when a user from the person table is deleted. The score table should have a reference to the user - pid which is used as the foreign key dependancy. It makes sense to me that the score is dependant upon the user so no user, no score.
create table `person` (
`id` int(10) unsigned not null auto_increment,
`name` varchar(50) null default null,
primary key (`id`)
)
collate='latin1_swedish_ci'
engine=innodb
auto_increment=4;
mysql> describe person;
+-------+------------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-------+------------------+------+-----+---------+----------------+
| id | int(10) unsigned | NO | PRI | NULL | auto_increment |
| name | varchar(50) | YES | | NULL | |
+-------+------------------+------+-----+---------+----------------+
create table `score` (
`id` int(10) unsigned not null auto_increment,
`bmi` int(10) unsigned not null default '0',
`weight` int(10) unsigned not null default '0',
`pid` int(10) unsigned not null default '0',
primary key (`id`),
index `pid` (`pid`),
constraint `fk_sc_pid` foreign key (`pid`) references `person` (`id`) on update cascade on delete cascade
)
collate='latin1_swedish_ci'
engine=innodb
auto_increment=4;
mysql> describe score;
+--------+------------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+--------+------------------+------+-----+---------+----------------+
| id | int(10) unsigned | NO | PRI | NULL | auto_increment |
| bmi | int(10) unsigned | NO | | 0 | |
| weight | int(10) unsigned | NO | | 0 | |
| pid | int(10) unsigned | NO | MUL | 0 | |
+--------+------------------+------+-----+---------+----------------+
mysql> select * from person;
+----+------+
| id | name |
+----+------+
| 1 | bob |
| 2 | rita |
| 3 | sue |
+----+------+
mysql> select * from score;
+----+-----+--------+-----+
| id | bmi | weight | pid |
+----+-----+--------+-----+
| 1 | 34 | 34 | 1 |
| 2 | 56 | 41 | 2 |
| 3 | 56 | 77 | 3 |
+----+-----+--------+-----+
mysql> delete from person where id=3;
Query OK, 1 row affected (0.00 sec)
/* delete a user, the score disappears too which makes sense */
mysql> select * from score;
+----+-----+--------+-----+
| id | bmi | weight | pid |
+----+-----+--------+-----+
| 1 | 34 | 34 | 1 |
| 2 | 56 | 41 | 2 |
+----+-----+--------+-----+
Your issue is semantic understanding of the task, rather than syntax. Intuitively your relation looks wrong. It is unlikely, that a particular score, say 75kg and bmi of 20 will need to have a many relations link to people with the same score. This would be arbitary. More likely, your want, a person to have different scores over time, then when you delete a person, you want their associated values deleted. So table relation should be:
person
- id (Primary Key)
- name
score
- id (Primary Key)
- bmi
- weight
- scoreDate
- personID (Foreign Key to person)
A score date would be a helpful addition.
This structure will allow a person to have a history of many score and see the fluctuation of their weight and body mass index over time. A semantically helpful task that resonates with reality, and therefore follows the notions of entity analysis and table structures following the real world application.
Helpful discussion of ERD and table structure levels and relations
In you tables, "person" table is having reference(FK) of "score" table so when you delete a record in "score" table mysql search related record in "users" table to delete.
but "score" table dose not have any reference(FK) of "person" table.
You can try below table structure if you want to delete score record when person record will be delete but person record will be still safe if score record will be delete
person
- id (PK)
- name
score
- id (PK)
- person_id (FK)
- bmi
- weight
I've two tables, the first table contains information on the ideas submitted by user and the second table contains information on the file attachments that are part of the idea. An idea submitted by the user can have 0 or any number of attachments.
Table 1:
-------------------------------------
Id Title Content Originator
-------------------------------------
1 aaa bbb John
2 ccc ddd Peter
--------------------------------------
Table 2:
---------------------------------------------
Id Idea_id Attachment_name
---------------------------------------------
1 1 file1.doc
2 1 file2.doc
3 1 file3.doc
4 2 user2.doc
---------------------------------------------
Table 1 primary key is Id and table 2 primary key is Id as well. Idea_id is the foreign key in table 2 mapping to table 1 Id.
I'm trying to display all the ideas, along with their attachments in a html page. So what I've been doing is: get all the ideas from Table 1 and then for each idea record, retrieve the attachment records from table 2.It seems to be extremely inefficient. Could this be optimized so that I can retrieve idea records and their corresponding attachment records in one query?
I tried with left outer join(Table 1 left outer join Table 2) but that would give me three records for Id = 1 in table 1. I'm looking for a SQL query to club idea detail and attachment names in 1 row to make HTML page processing efficient. Otherwise, What would be the best solution for this?
If you want to get all attachments along with all ideas, you may use GROUP_CONCAT. such as
SELECT *, (SELECT GROUP_CONCAT(attachment_name separator ', ') FROM TABLE2 WHERE idea_id = TABLE1.id) attachments FROM TABLE1
I probably missed the point but a left join should bring back all the records
create table `ideas` (
`id` int(10) unsigned not null auto_increment,
`title` varchar(50) not null,
`content` varchar(50) not null,
`originator` varchar(50) not null,
primary key (`id`)
)
engine=innodb
auto_increment=3;
create table `attachments` (
`id` int(10) unsigned not null auto_increment,
`idea_id` int(10) unsigned not null default '0',
`attachment` varchar(50) not null default '0',
primary key (`id`),
index `idea_id` (`idea_id`),
constraint `fk_ideas` foreign key (`idea_id`) references `ideas` (`id`) on update cascade on delete cascade
)
engine=innodb
auto_increment=5;
mysql> select * from ideas;
+----+----------------+-----------+-----------------+
| id | title | content | originator |
+----+----------------+-----------+-----------------+
| 1 | Flux capacitor | Rubbish | Doc |
| 2 | Star Drive | Plutonium | Professor Frink |
+----+----------------+-----------+-----------------+
mysql> select * from attachments;
+----+---------+------------------------------+
| id | idea_id | attachment |
+----+---------+------------------------------+
| 1 | 1 | Flux capacitor schematic.jpg |
| 2 | 1 | Sensors.docx |
| 3 | 1 | fuel.docx |
| 4 | 2 | plans.jpg |
+----+---------+------------------------------+
mysql> select * from ideas i
-> left outer join attachments a on a.idea_id=i.id;
+----+----------------+-----------+-----------------+------+---------+------------------------------+
| id | title | content | originator | id | idea_id | attachment |
+----+----------------+-----------+-----------------+------+---------+------------------------------+
| 1 | Flux capacitor | Rubbish | Doc | 1 | 1 | Flux capacitor schematic.jpg |
| 1 | Flux capacitor | Rubbish | Doc | 2 | 1 | Sensors.docx |
| 1 | Flux capacitor | Rubbish | Doc | 3 | 1 | fuel.docx |
| 2 | Star Drive | Plutonium | Professor Frink | 4 | 2 | plans.jpg |
+----+----------------+-----------+-----------------+------+---------+------------------------------+
I'm not a SQL veteran so please excuse me if this is obvious; I'm learning.
I have two tables in a database for a wedding invite system; guests and invites. One invite (invitation) can contain many guests.
For purposes of creating a mail merge for the invites, I'm trying to select the firstname and lastname from the guest table, where the guest's inviteID is the same as the others; effectively returning on row of data containing the inviteID's data and a column each for the names of the guests.
My problem is I can return the data, but across multiple rows which won't work for the mail-merge. I can create a PHP script to do a work-around, but I would like to learn how this could be achieved in pure SQL.
Can anybody shed some light? Can this be done? Is this sheer madness?
Hoping to achieve:
*************************** 1. row ***************************
inviteID: 39
inviteURLSlug: thewinnetts
....
guestFirstName1: Sid
guestSurname1: Winnett
guestFirstName2: Claire
guestSurname2: Winnett
'invite' table:
+---------------------+--------------+
| Field | Type |
+---------------------+--------------+
| inviteID | int(11) |
| inviteURLSlug | varchar(64) |
| inviteQRValue | varchar(255) |
| inviteQRImageURL | varchar(255) |
| inviteAddress1 | varchar(32) |
| inviteAddress2 | varchar(32) |
| inviteAddress3 | varchar(32) |
| inviteCity | varchar(32) |
| inviteCounty | varchar(32) |
| inviteCountry | varchar(32) |
| invitePostcode | varchar(16) |
| inviteDateSend | datetime |
| inviteDateResponded | datetime |
| inviteCreated | datetime |
| inviteUpdated | timestamp |
+---------------------+--------------+
'guest' table:
+-------------------+--------------+
| Field | Type |
+-------------------+--------------+
| guestID | int(11) |
| inviteID | int(11) |
| guestFirstName | varchar(32) |
| guestSurname | varchar(32) |
| guestSide | varchar(8) |
| guestAttending | tinyint(1) |
| guestEmail | varchar(255) |
| guestPhone | varchar(32) |
| guestMobile | varchar(16) |
| guestAddress1 | varchar(32) |
| guestAddress2 | varchar(32) |
| guestAddress3 | varchar(32) |
| guestCity | varchar(32) |
| guestCounty | varchar(32) |
| guestCountry | varchar(32) |
| guestPostCode | varchar(16) |
| guestProfilePhoto | varchar(64) |
| guestFoodVeg | tinyint(1) |
| guestFoodReq | varchar(255) |
| guestTwitter | varchar(15) |
| guestFacebook | varchar(32) |
| guestPlusone | int(1) |
| guestCreated | datetime |
| guestUpdated | timestamp |
+-------------------+--------------+
Failed Join attempt and cropped results sample:
SELECT * FROM guest INNER JOIN invite on guest.inviteID = invite.inviteID \G
*************************** 64. row ***************************
guestID: 72
inviteID: 39
guestFirstName: Claire
guestSurname: Winnett
.......
*************************** 65. row ***************************
guestID: 73
inviteID: 39
guestFirstName: Sid
guestSurname: Winnett
.......
To achieve those results will require additional processing in PHP.
To do so, modify your query to this:
SELECT i.*,
g.guestFirstName,
g.guestSurname
GROUP_CONCAT(DISTINCT g.guestFirstName, '|', g.guestSurname ORDER BY g.guestSurname DESC) AS names
FROM invite i
INNER JOIN guest g ON i.inviteID = g.inviteID;
making sure to return your results as an array. From there, convert the concatenated results into an array then iterate through them to set the custom key name and corresponding value (assumes your query results are in array format with the variable name $queryresults):
$names = explode(',' $queryresults['names']);
unset($queryresults['names']);
$i = 1;
foreach ($names as $name) {
$split_name = str_split("|", $name);
$queryresults['guestFirstName' . $i] = $split_name[0];
$queryresults['guestSurname' . $i] = $split_name[1];
$i++;
}
This should give you your desired results.
SQL is not good at this sort of thing. It wants to work in sets, where all the items in the set are the same. You are asking for two items within the set to be smooshed together. Here is a possible solution:
SELECT
t1.inviteID,
t1.guestID,
t1.guestFirstName,
t1.guestSurname,
t2.guestFirstName AS guestFirstName2,
t2.guestSurname AS guestSurname2
FROM
guests as t1
LEFT OUTER JOIN
guests as t2
ON t1.inviteID = t2.inviteID
AND t1.guestID <> t2.guestID
WHERE
t1.guestID = (select min(t3.guestID) from guests as t3 where t3.inviteID = t1.inviteID)
;
The guests table is used twice, once to provide the first guest on each invite, and a second time, using a LEFT OUTER JOIN to provide the second. The LEFT OUTER ensures you still get the first even if there isn't a second. The other criteria are there to ensure you don't join a row to itself, and you only output the firsts, with the seconds attached (and not the other way around).
Here is a sample fiddle (in MySQL)
Is something like this what you are looking for?
Updated after your comment.
SELECT GROUP_CONCAT( DISTINCT `guest`.`guestFirstName`,`guest`.`guestSurname`, `invite`.`inviteURLSlug` ) FROM `guest`
LEFT JOIN `invite` ON `invite`.`inviteID` = `guest`.`inviteID`
WHERE `invite`.`inviteID` = 5
I just made two simple tables with minimal information for testing, but is easily expandable to whatever you have/want.
You are going to have some fields repeated since the number of rows is going to be related to the number of guests.
The following queries use 80% or more CPU and can take more than 1 minute to complete.
My question: Is there anything wrong with my queries that would cause CPU usage like that? Can I decrease CPU usage and query time by optimizing the MySQL server conf?
Query 1 (loan_history contains 2.6 million records)
SELECT officer, SUM(balance) as balance
FROM loan_history
WHERE bank_id = '1'
AND date ='2013-07-04'
AND officer IS NOT NULL
AND officer <> ''
GROUP BY officer
ORDER BY officer;
Query 2 (loan_history contains 2.6 million records)
SELECT SUM(weighted_interest_rate) as total
FROM (SELECT balance, tmp1.balance_sum,
(balance / tmp1.balance_sum * interest_rate) as weighted_interest_rate
FROM loan_history,
(SELECT SUM(balance) balance_sum FROM loan_history
WHERE date = '2013-07-04'
AND bank_id = '1') as tmp1
WHERE date = '2013-07-04'
AND bank_id = '1') tmp2
Table information:
CREATE TABLE `loan_history` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`bank_id` int(11) DEFAULT NULL,
`loan_purpose_id` int(11) DEFAULT NULL,
`date` date NOT NULL,
`credit_grade` varchar(5) COLLATE utf8_unicode_ci DEFAULT NULL,
`interest_rate` decimal(5,2) NOT NULL,
`officer` varchar(5) COLLATE utf8_unicode_ci DEFAULT NULL,
`balance` decimal(10,2) NOT NULL,
`start_date` date DEFAULT NULL,
`days_delinquent` int(11) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `IDX_9F5FE3F11C8FB41` (`bank_id`),
KEY `IDX_9F5FE3F6F593857` (`loan_purpose_id`),
KEY `date` (`date`),
KEY `credit_grade` (`credit_grade`),
KEY `officer` (`officer`),
KEY `start_date` (`start_date`),
KEY `days_delinquent` (`days_delinquent`),
KEY `interest_rate` (`interest_rate`),
KEY `balance` (`balance`),
CONSTRAINT `FK_9F5FE3F11C8FB41` FOREIGN KEY (`bank_id`) REFERENCES `bank` (`id`),
CONSTRAINT `FK_9F5FE3F6F593857` FOREIGN KEY (`loan_purpose_id`) REFERENCES `loan_purpose` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2630634 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
Query 1 EXPLAIN:
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
| 1 | SIMPLE | loan_history | index_merge | IDX_9F5FE3F11C8FB41,date,officer | date,IDX_9F5FE3F11C8FB41 | 3,5 | NULL | 4829 | Using intersect(date,IDX_9F5FE3F11C8FB41); Using where; Using temporary; Using filesort |
Query 2 EXPLAIN:
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra
| 1 | PRIMARY | <derived2> | ALL | NULL | NULL | NULL | NULL | 8236 |
| 2 | DERIVED | <derived3> | system | NULL | NULL | NULL | NULL | 1 |
| 2 | DERIVED | loan_history | index_merge | IDX_9F5FE3F11C8FB41,date | date,IDX_9F5FE3F11C8FB41 | 3,5 | NULL | 4829 | Using intersect(date,IDX_9F5FE3F11C8FB41); Using where; Using index |
| 3 | DERIVED | loan_history | index_merge | IDX_9F5FE3F11C8FB41,date | date,IDX_9F5FE3F11C8FB41 | 3,5 | NULL | 4829 | Using intersect(date,IDX_9F5FE3F11C8FB41); Using where; Using index |
My.cnf file:
default-storage-engine=MyISAM
interactive_timeout=300
key_buffer_size=256M
key_cache_block_size=4096
max_heap_table_size=128M
max_join_size=1000000000
max_allowed_packet=32M
open_files_limit=4096
query_cache_size=256M
query_cache_limit=10240M
query_cache_type=1
table_cache=256
thread_cache_size=100
tmp_table_size=128M
wait_timeout=7800
max_user_connections=50
join_buffer_size=256K
sort_buffer_size=4M
read_rnd_buffer_size=1M
innodb_open_files=300
innodb_log_file_size=256M
innodb_log_buffer_size=8M
innodb_file_per_table=1
innodb_additional_mem_pool_size=20M
innodb_flush_log_at_trx_commit=0
innodb_flush_method=O_DIRECT
innodb_support_xa=0
innodb_thread_concurrency=0
innodb_buffer_pool_size=3000M
The sum() and GROUP BY from the first query could be taking some time but I don't think there is much you can do there.
In the second query your FROM (SELECT.... is probably hitting the system pretty hard, I would recommend turning
(SELECT balance, tmp1.balance_sum,
(balance / tmp1.balance_sum * interest_rate) as weighted_interest_rate
FROM loan_history,
(SELECT SUM(balance) balance_sum FROM loan_history
WHERE date = '2013-07-04'
AND bank_id = '1') as tmp1
WHERE date = '2013-07-04'
AND bank_id = '1')
into a view or figuring out how to do it with JOINs
Please tell us how much does exactly each one take. More than 1 minute each isn't that much indicative.
Any how, From MySQL manual
When tuning a MySQL server, the two most important variables to configure are key_buffer_size and table_cache. You should first feel confident that you have these set appropriately before trying to change any other variables.
Also, take a look here.
As for optimization, first try a composite index.
i was looking for a way to combine different mysql queries in a php file so this is my code :
$sql_query = "SELECT b.*,
u.username AS MY_Sender
FROM table_users u,
table_blogs b
WHERE b.reciever = '0'
AND
u.user_id = b.sender
UNION
SELECT b.*,
u2.username AS MY_Recipient
FROM table_users u2,
table_blogs b
WHERE b.reciever != '0'
AND
u2.user_id = b.reciever
";
this code works fine unless it cant fetch MY_Recipient
in the above code i need to fetch both sender of blog post and the receiver
is it wrong to use Union to do so ?!
I have made a guess at your table structure, and produced something similar. Right or wrong, it might at least help arrive at a suitable solution for you.
Two tables, users and blogs:
CREATE TABLE `users` (
`id` int(11) NOT NULL auto_increment,
`username` varchar(255) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB;
CREATE TABLE `blogs` (
`id` int(11) NOT NULL auto_increment,
`sender` int(11) NOT NULL,
`receiver` int(11) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB;
Add some users:
INSERT INTO `users` (username) VALUES
('Alice'), ('Bob'), ('Carol'), ('Eve');
Add blog entries for some users:
INSERT INTO `blogs` (sender, receiver) VALUES
(1,2), (2,1), (3,4), (4,3), (1,4), (4,1);
For each blog entry, list the sender and receiver:
SELECT
b.id,
b.sender AS sender_id,
b.receiver AS receiver_id,
us.username AS sender_name,
ur.username AS receiver_name
FROM blogs AS b
JOIN users AS us ON us.id = b.sender
JOIN users AS ur ON ur.id = b.receiver
ORDER BY b.id;
+----+-----------+-------------+-------------+---------------+
| id | sender_id | receiver_id | sender_name | receiver_name |
+----+-----------+-------------+-------------+---------------+
| 1 | 1 | 2 | Alice | Bob |
| 2 | 2 | 1 | Bob | Alice |
| 3 | 3 | 4 | Carol | Eve |
| 4 | 4 | 3 | Eve | Carol |
| 5 | 1 | 4 | Alice | Eve |
| 6 | 4 | 1 | Eve | Alice |
+----+-----------+-------------+-------------+---------------+
UPDATE 1
table_blogs should probably look like this:
CREATE TABLE IF NOT EXISTS `table_blogs` (
`bid` int(10) NOT NULL AUTO_INCREMENT,
`content` varchar(255) DEFAULT NULL,
`date` varchar(14) DEFAULT NULL,
`sender` int(10) NOT NULL,
`reciever` int(10) NOT NULL,
CONSTRAINT `fk_sender`
FOREIGN KEY (`sender` )
REFERENCES `table_users` (`id` )
ON DELETE CASCADE
ON UPDATE CASCADE,
CONSTRAINT `fk_receiver`
FOREIGN KEY (`receiver` )
REFERENCES `table_users` (`id` )
ON DELETE CASCADE
ON UPDATE CASCADE,
PRIMARY KEY (`bid`)
) ENGINE=MyISAM AUTO_INCREMENT=1 ;
The CONSTRAINT clauses will prevent inserting values for users which don't exist, and will delete entries when users are deleted from the user table.
UPDATE 2
I think this is what you want, but as KM and bobince have stated in the comments, it violates foreign key constraints, which is not really a good idea. So, assuming no foreign key constraints, here's some additional inserts and a modified query:
INSERT INTO `blogs` (sender, receiver) VALUES
(1,0), (0,1), (4,0), (0,4), (2,0), (0,2);
SELECT
b.id,
b.sender AS sender_id,
b.receiver AS receiver_id,
IFNULL(us.username, ur.username) AS sender_name,
IFNULL(ur.username, us.username) AS receiver_name
FROM blogs AS b
LEFT JOIN users AS us ON us.id = b.sender
LEFT JOIN users AS ur ON ur.id = b.receiver
ORDER BY b.id;
+----+-----------+-------------+-------------+---------------+
| id | sender_id | receiver_id | sender_name | receiver_name |
+----+-----------+-------------+-------------+---------------+
| 1 | 1 | 2 | Alice | Bob |
| 2 | 2 | 1 | Bob | Alice |
| 3 | 3 | 4 | Carol | Eve |
| 4 | 4 | 3 | Eve | Carol |
| 5 | 1 | 4 | Alice | Eve |
| 6 | 4 | 1 | Eve | Alice |
| 7 | 1 | 0 | Alice | Alice |
| 8 | 0 | 1 | Alice | Alice |
| 9 | 4 | 0 | Eve | Eve |
| 10 | 0 | 4 | Eve | Eve |
| 11 | 2 | 0 | Bob | Bob |
| 12 | 0 | 2 | Bob | Bob |
+----+-----------+-------------+-------------+---------------+
The field name should be the same
Rename My_sender and My_Recipient to "User" and the union will work.
What are you trying to do? You say there are two queries there, but it looks like the same query to me, just one of them having a different table alias.
The only purpose I can see for the UNION is to put all the rows with a zero-receiver before those without. But you can do that more simply by using a computed ORDER BY:
SELECT b.*, u.username
FROM table_blogs AS b
JOIN table_users AS u ON u.user_id=b.sender
ORDER BY b.receiver<>0
if there are no negative receiver IDs, you could change that to ORDER BY b.receiver as 0 would always come first, which would then be possible to index if you needed to;
ANSI JOIN is generally considered more readable than the old-school method of implicit joins in the WHERE conditions;
<> is preferable to !=, which is a non-standard MySQL synonym;
check the spelling of receiver.
For a union to work, the two select statements should return identical columns. This is where the query is failing.
You can do this in a single query, but if you want to use unions, the problem is that both queries need to have the same column names:
select b.*, u.username AS username, "sender" as type ...
select b.*, u2.username AS username, "recipient" as type...